class Solution {
public:
    int trap(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
      int l = 0;
      int r = n - 1;
      int result = 0;

      while (l < r) {
        if (A[l] < A[r]) {
          if (A[l + 1] < A[l]) {
            result += A[l] - A[l + 1];
            A[l + 1] = A[l];
          }
          ++l;
        } else {
          if (A[r - 1] < A[r]) {
            result += A[r] - A[r - 1];
            A[r - 1] = A[r];
          }
          --r;
        }
      }
      return result;

    }
};
